/**
 * @license
 * Copyright 2021 Du Tian Wei
 * SPDX-License-Identifier: Apache-2.0
 */

const express = require('express');
const { app } = require('electron');
const root = app.getAppPath() + "/static";
const eapp = express();
const fs = require('fs');
// var bodyParser = require('body-parser')
// var raw = bodyParser.raw({ type: '*/*' });

var getRawBody = require('raw-body');

let projectStatic = null;
function putFile(req, res, next) {
    let body = req.body;
    let path = req.url;
    let abpath = projectStatic._project.path + path;
    fs.writeFile(abpath, body, () => {
        console.log('writen to ' + abpath);
    });
    res.status(200).send();
}
function wrap(req, res, next) {
    if (!projectStatic) {
        res.status(503).send('未打开项目');
        return;
    }
    if (req.url.startsWith("/" + projectStatic._project.encodeName + "/")) {
        req.url = req.url.substr(projectStatic._project.encodeName.length + 1);
        res.set({
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': '*',
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Headers": "Content-Type,Access-Token",
            "Access-Control-Expose-Headers": "*"
        });
        if (req.method === 'OPTIONS') {
            res.set({ 'Allow': 'OPTIONS, GET, HEAD, POST, PUT' }).status(200).send();
        } else if (req.method === 'PUT') {
            // raw(req, res, () => {
            //     putFile(req, res, next);
            // });

            getRawBody(req, {
                length: req.headers['content-length'],
                limit: '8mb',
                // encoding: contentType.parse(req).parameters.charset
            }, function (err, buf) {
                if (err) return next(err)
                req.body = buf
                // next()
                putFile(req, res, next);
            })
        } else {
            return projectStatic(req, res, next);
        }
    } else {
        next();
    }
}
eapp.use('/project', wrap);
let servestatic = express.static(root);
function wrapStatic(req, res, next) {
    return servestatic(req, res, next);
}
eapp.use(wrapStatic);
function start(port, cb) {
    eapp.listen(port, () => {
        console.log(`listening at http://localhost:${port}`);
        if (cb) {
            cb(port);
        }
    });
}
function setProjectPath(info) {
    if (info) {
        projectStatic = express.static(info.path);
        console.log(info);
        info.encodeName = encodeURI(info.name);
        projectStatic._project = info;
    } else {
        projectStatic = null;
    }
}
module.exports = {
    start, setProjectPath
};